<template>
  <span>{{ label }}</span>
</template>

<script>
  import { ajaxGetDictItems } from '@/api/api'
  import { getDictItemsFromCache } from '@/components/dict/JDictSelectUtil'

  export default {
    name: "JDictLabel",
    props: {
      value: {
        type: [String, Number, Array],
        required: false,
        default: ''
      },
      dictCode: {
        type: String,
        required: true
      }
    },
    data() {
      return {
        label: '',
        dictOptions: []
      }
    },
    watch: {
      value: {
        immediate: true,
        handler() {
          this.initDictLabel()
        }
      },
      dictCode: {
        immediate: true,
        handler() {
          this.initDictData()
        }
      }
    },
    methods: {
      initDictData() {
        // 优先从缓存中读取字典配置
        if (getDictItemsFromCache(this.dictCode)) {
          this.dictOptions = getDictItemsFromCache(this.dictCode)
          this.initDictLabel()
          return
        }

        // 根据字典Code, 初始化字典数组
        ajaxGetDictItems(this.dictCode, null).then((res) => {
          if (res.success) {
            this.dictOptions = res.result
            this.initDictLabel()
          }
        })
      },
      initDictLabel() {
        if (!this.dictOptions || this.dictOptions.length === 0 || !this.value) {
          this.label = ''
          return
        }

        let values = this.value
        if (!Array.isArray(values)) {
          values = [this.value]
        }

        let labels = []
        for (let val of values) {
          if (val === null || val === undefined) continue;
          
          let dictItem = this.dictOptions.find(item => item.value === val.toString())
          if (dictItem) {
            labels.push(dictItem.text || dictItem.label || dictItem.title || dictItem.value)
          }
        }

        this.label = labels.join(', ')
      }
    }
  }
</script> 